package com.dmyang.p2pchat.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dmyang.p2pchat.R;
import com.dmyang.p2pchat.adapter.ChatAdapter;
import com.dmyang.p2pchat.bean.Message;
import com.dmyang.p2pchat.bean.User;
import com.dmyang.p2pchat.comm.constant.GlobalConstant;
import com.dmyang.p2pchat.database.ChatContentDao;
import com.dmyang.p2pchat.database.UserListDao;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by brss on 2017/10/29.
 */

public class ChatActivity extends AppCompatActivity {
    private Context mContext;
    private ListView lv_simple4chat;
    private List chatList;
    private ChatAdapter chatAdapter;
    private ChatContentDao chatContentDao;

    private EditText etChatContent;
    private Button btnSend;

    private String targetIpAndPort;//对方的ip和端口

    //负责每秒发一个Message出去，handler收到后，就更新管理ListView的Adapter
    private Thread sendHandlerThread = new Thread() {
        @Override
        public void run() {
            while (true) {
                android.os.Message msg = new android.os.Message();
                msg.obj = "whatever";
                msg.what = 1;
                handler.sendMessage(msg);
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    //更新ui(更新聊天信息)
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            UserListDao userListDao = new UserListDao(mContext);
            chatList = chatContentDao.queryByIpAndPort(targetIpAndPort);//targetIpAndPort是查询聊天记录的主键，意思是聊天记录是归属于这条主键的
            chatAdapter.refresh(chatList);
            //System.out.println("Chat UI更新一次");
        }
    };
    private String willSendStr = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        mContext = this;

        //找到控件
        etChatContent = (EditText) findViewById(R.id.edit_text);//发送内容的按钮
        btnSend = (Button) findViewById(R.id.btn_send);//发送按钮

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        targetIpAndPort = bundle.getString("ipAndPort");
        System.out.println("OnCreate中收到的数据是：" + targetIpAndPort);
        //找到listView
        lv_simple4chat = (ListView) findViewById(R.id.lv_simple4chat);

        //获取之前的聊天数据，用list封装,先造假数据（这里就不用Util了）
        chatList = new ArrayList();
        chatContentDao = new ChatContentDao(mContext);
        chatList = chatContentDao.queryByIpAndPort(targetIpAndPort);//targetIpAndPort是查询聊天记录的主键，意思是聊天记录是归属于这条主键的
        //创建一个adapter
        chatAdapter = new ChatAdapter(mContext, chatList);
        //将adapter设置给listView
        lv_simple4chat.setAdapter(chatAdapter);

        sendHandlerThread.start();//开启更新ui的线程。（相当于脉搏）

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                System.out.println(etChatContent.getText().toString());
                if (etChatContent.getText().toString().length() > 0) {
                    Message message = new Message(targetIpAndPort, new Date(), "你", etChatContent.getText().toString());
                    chatContentDao.add(message);
                    //网络发生的文字
                    willSendStr = "CHATCONTENT" + ","+ GlobalConstant.myNickName + "," +etChatContent.getText().toString();
                    sendClass sendClass = new sendClass();
                    sendClass.start();
                    etChatContent.setText("");
                } else {
                    Toast.makeText(mContext, "发送内容不能为空！", Toast.LENGTH_SHORT);
                    return;
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sendHandlerThread = null;
        System.out.println("ChatActivity的onDestroy执行了。");
    }

    /**
     * 发送数据的线程（网络通信）
     */
    public class sendClass extends Thread {
        @Override
        public void run() {
            DatagramSocket socket;
            try {
                //创建DatagramSocket对象并指定一个端口号，注意，如果客户端需要接收服务器的返回数据,
                //还需要使用这个端口号来receive，所以一定要记住
                String targetIp = targetIpAndPort.split(":")[0];
                String targetProt = targetIpAndPort.split(":")[1];
                int port = Integer.parseInt(targetProt);
                /////【】【】【】【】【】【】【】【】【】【】【】【】【】【这里没有port】
                socket = new DatagramSocket();
                //使用InetAddress(Inet4Address).getByName把IP地址转换为网络地址
                //"192.168.1.105"
                InetAddress serverAddress = InetAddress.getByName(targetIp);
                String str = willSendStr;//设置要发送的报文
                byte data[] = str.getBytes();//把字符串str字符串转换为字节数组
                //创建一个DatagramPacket对象，用于发送数据。
                //参数一：要发送的数据  参数二：数据的长度  参数三：服务端的网络地址  参数四：服务器端端口号
                DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, port);
                socket.send(packet);//把数据发送到服务端。
                socket.close();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}